<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import {CloseBold} from "@element-plus/icons-vue";
import {articleAPI} from "@/apis/index.js";
import { useUserStore } from '@/stores/user.js'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 编辑模式检测
const isEditMode = computed(() => !!route.params.articleId)
const articleId = computed(() => route.params.articleId)

const loading = ref(false)
const submitLoading = ref(false)

// 数据
const formData = reactive({
  title: '',
  content: '',
  parentBoardId: '',
  boardId: '',
  isNotice: false,
  allowComment: true,
  topExpireTime: null, // 通知到期时间
  expireTime: null, // 文章到期时间
  images: []
})

// 用户信息
const currentUser = computed(() => userStore.userInfo)

// 父级板块信息
const parentBoardOptions = ref([])

// 子级板块信息
const childBoardOptions = ref({})

// 获取板块信息
const fetchBoardInfo = async () => {
  try {
    const response = await articleAPI.getBoards()
    if (response.status === 'success') {
      // 过滤掉 Notice
      const filteredData = response.data.filter(board => board.pBoardId !== 1)
      
      // 父级板块数据
      parentBoardOptions.value = filteredData.map(board => ({
        value: board.pBoardId,
        label: board.boardName
      }))
      
      // 子级板块数据
      const childBoards = {}
      filteredData.forEach(board => {
        if (board.children && board.children.length > 0) {
          childBoards[board.pBoardId] = board.children.map(child => ({
            value: child.boardId,
            label: child.boardName
          }))
        } else {
          childBoards[board.pBoardId] = []
        }
      })
      childBoardOptions.value = childBoards
    }
  } catch (error) {
    console.log(error)
  }
}

// 当前可选的子级板块
const currentChildBoards = computed(() => {
  if (!formData.parentBoardId) return []
  return childBoardOptions.value[formData.parentBoardId] || []
})

// 监听父级板块变化，清空子级板块选择（编辑模式下不清空）
watch(() => formData.parentBoardId, (newVal, oldVal) => {
  // 只在非编辑模式或者用户主动更改时清空子板块
  if (!isEditMode.value && oldVal !== undefined) {
    formData.boardId = ''
  }
})

// 图片上传相关
const uploadRef = ref()
const imageList = ref([]) // 存储图片文件对象和预览URL
const deletedImageUrls = ref([]) // 存储待删除的图片URL

// 图片上传
const handleImageUpload = async (file) => {
  if (imageList.value.length >= 4) {
    ElMessage.error('Up to 4 images can be uploaded!')
    return false
  }

  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('Only image files can be uploaded!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('Image size cannot exceed 5MB!')
    return false
  }

  // 创建本地预览URL
  const previewUrl = URL.createObjectURL(file)
  
  // 存储文件对象和预览URL
  imageList.value.push({
    file: file,
    previewUrl: previewUrl,
    isUploaded: false // 标记为未上传
  })
  
  ElMessage.success('Image added successfully!')
  
  return false
}

// 删除图片
const handleImageRemove = async (index) => {
  const imageItem = imageList.value[index]
  
  // 如果是已上传的图片（编辑模式），标记为待删除
  if (imageItem.isUploaded && imageItem.imageUrl) {
    // 添加到待删除列表
    deletedImageUrls.value.push(imageItem.imageUrl)
    ElMessage.success('Image marked for deletion!')
  } else {
    // 如果是本地预览图片，释放URL对象
    if (imageItem.previewUrl) {
      URL.revokeObjectURL(imageItem.previewUrl)
    }
    ElMessage.success('Image removed successfully!')
  }

  imageItem.isDeleted = true
}

// 表单校验
const validateForm = () => {
  if (!formData.title.trim()) {
    ElMessage.error('Please enter title')
    return false
  }
  if (!formData.content.trim()) {
    ElMessage.error('Please enter content')
    return false
  }
  if (!formData.parentBoardId) {
    ElMessage.error('Please select a parent board')
    return false
  }
  if (!formData.boardId) {
    ElMessage.error('Please select a sub board')
    return false
  }
  return true
}

// 上传图片
const uploadImages = async () => {
  const uploadPromises = []
  const imageUrls = []
  
  for (const imageItem of imageList.value) {
    // 跳过已删除的图片
    if (imageItem.isDeleted) continue
    
    if (!imageItem.isUploaded && imageItem.file) {

      const formData = new FormData()
      formData.append('image', imageItem.file)
      
      const uploadPromise = articleAPI.uploadImage(formData).then(response => {
        if (response.status === 'success') {
          return response.data.imageUrl
        }
        throw new Error('Upload failed')
      })
      
      uploadPromises.push(uploadPromise)
    } else if (imageItem.isUploaded && imageItem.imageUrl) {

      imageUrls.push(imageItem.imageUrl)
    }
  }
  
  // 等待所有新图片上传完成
  if (uploadPromises.length > 0) {
    try {
      const newImageUrls = await Promise.all(uploadPromises)
      imageUrls.push(...newImageUrls)
    } catch (error) {
      throw new Error('Some images failed to upload')
    }
  }
  
  return imageUrls
}

// 删除图片
const RemoveImages = async () => {
  if (deletedImageUrls.value.length === 0) return
  
  const deletePromises = deletedImageUrls.value.map(imageUrl => {
    return articleAPI.deleteImage({
      image_url: imageUrl
    }).catch(error => {
      console.log(`Failed to delete image: ${imageUrl}`, error)
      return null
    })
  })
  
  try {
    await Promise.all(deletePromises)
    ElMessage.success(`Successfully deleted ${deletedImageUrls.value.length} image(s)`)
  } catch (error) {
    ElMessage.warning('Some images failed to delete from server')
  }
}

// 发布帖子
const submitPost = async () => {

  if (!validateForm()) return
  
  try {
    submitLoading.value = true
    // 先删除服务器上标记为删除的图片
    await RemoveImages()
    
    // 然后上传所有新图片
    const imageUrls = await uploadImages()
    
    // 构建提交数据，按照后端要求的格式
    const postData = {
      pBoardId: formData.parentBoardId, // 父级板块ID
      boardId: formData.boardId, // 子级板块ID
      topType: formData.isNotice,
      title: formData.title,
      content: formData.content,
      allowComments: formData.allowComment, // 是否允许评论
      imageList: imageUrls // 图片URL数组
    }

    // 如果是通知且设置了到期时间，添加到期时间参数
    if (formData.isNotice && formData.topExpireTime) {
      postData.topExpireTime = formData.topExpireTime
    }
    // 如果设置了文章到期时间，添加到期时间参数
    if (formData.expireTime) {
      postData.expireTime = formData.expireTime
    }
    
    // 如果是编辑模式，添加文章ID
    if (isEditMode.value) {
      postData.articleId = articleId.value
    }
    
    let response
    if (isEditMode.value) {
      // 编辑模式：调用编辑文章API
      response = await articleAPI.editArticle(postData)
    } else {
      // 新建模式：调用发布文章API
      response = await articleAPI.publishArticle(postData)
    }
    
    if (response.status === 'success') {
      const successMessage = response.info
      
      ElMessage.success(successMessage)
      
      if (isEditMode.value) {
        // 编辑模式：返回文章详情页
        router.push(`/post/${articleId.value}`)
      } else {
        // 新建模式：重置表单并跳转到新文章详情页
        formData.title = ''
        formData.content = ''
        formData.parentBoardId = ''
        formData.boardId = ''
        formData.isNotice = false
        formData.allowComment = true
        formData.topExpireTime = null
        formData.expireTime = null
        
        // 清理图片预览URL
        imageList.value.forEach(imageItem => {
          if (imageItem.previewUrl) {
            URL.revokeObjectURL(imageItem.previewUrl)
          }
        })
        imageList.value = []
        deletedImageUrls.value = []
        
        // 重定向到文章详情页
        if (response.data) {
          router.push(`/post/${response.data}`)
        }
      }
    }
  } catch (error) {
    ElMessage.error('Failed to upload images or submit post')
  } finally {
    submitLoading.value = false
  }
}

// 取消发布
const cancelPost = () => {
  router.back()
}

// 组件挂载时获取板块信息
onMounted(async () => {
  loading.value = true
  await fetchBoardInfo()
  if (isEditMode.value) {
    await fetchArticleDetail()
  }
  loading.value = false
})

// 获取文章详情并预填充表单
const fetchArticleDetail = async () => {
  if (!isEditMode.value) return
  try {
    const response = await articleAPI.getArticleDetail({
      articleId: articleId.value
    })
    
    if (response.status === 'success' && response.data) {
      const article = response.data
      
      // 预填充表单数据
      formData.title = article.title
      formData.content = article.content
      formData.parentBoardId = article.pBoardId
      formData.boardId = article.boardId
      formData.isNotice = article.topType
      formData.allowComment = article.allowComments
      formData.topExpireTime = article.topExpireTime
      formData.expireTime = article.expireTime
      
      // 预填充图片列表
      if (article.imageList && article.imageList.length > 0) {
        imageList.value = article.imageList.map(url => ({
          imageUrl: url.trim(),
          isUploaded: true, // 标记为已上传
          previewUrl: null,
          file: null
        }))
      }
    }
  } catch (error) {
    console.log(error)
    router.back()
  }
}
</script>

<template>
  <div class="container-body edit-post-body">
    <!-- 导航栏 -->
    <div class="board-info">
      <router-link to="/" class="a-link">Home Page</router-link>
      <el-icon><ArrowRight/></el-icon>
      <span>{{ isEditMode ? 'Edit Post' : 'New Post' }}</span>
    </div>
    <div class="edit-container" v-loading="loading">
      <!-- 左侧区域 -->
      <div class="left-panel">
        <!-- 标题输入 -->
        <div class="form-item">
          <label class="form-label">Title</label>
          <el-input
            v-model="formData.title"
            placeholder="Please enter post title"
            maxlength="100"
            show-word-limit
            size="large"
          />
        </div>

        <!-- 内容输入 -->
        <div class="form-item">
          <label class="form-label">Content</label>
          <el-input
            v-model="formData.content"
            type="textarea"
            placeholder="Please enter post content"
            :rows="12"
            maxlength="5000"
            show-word-limit
            resize="none"
          />
        </div>

        <!-- 图片上传 -->
        <div class="form-item">
          <label class="form-label">Image Upload</label>
          <div class="upload-container">
            <el-upload
              ref="uploadRef"
              :before-upload="handleImageUpload"
              :show-file-list="false"
              accept="image/*"
              multiple
              :disabled="imageList.length >= 4"
            >
              <el-button 
                type="primary" 
                :icon="Plus"
                :disabled="imageList.length >= 4"
              >
                {{ imageList.length >= 4 ? 'Upload Limit Reached' : 'Upload Images' }}
              </el-button>
            </el-upload>
            <span class="upload-tip">Support jpg, png, gif formats, single image no more than 5MB, up to 4 images</span>
          </div>
          
          <!-- 图片预览 -->
          <div v-if="imageList.filter(item => !item.isDeleted).length > 0" class="image-preview">
            <div
              v-for="(imageItem, index) in imageList"
              :key="index"
              v-show="!imageItem.isDeleted"
              class="preview-item"
              :class="{ 'deleted-preview': imageItem.isDeleted }"
            >
              <el-image :src="imageItem.previewUrl || imageItem.imageUrl" alt="Preview Image" />
              <div class="preview-overlay">
                <el-button
                  type="danger"
                  :icon="CloseBold"
                  circle
                  size="small"
                  @click="handleImageRemove(index)"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧面板 -->
      <div class="right-panel">
        <!-- 选择板块 -->
        <div class="form-item">
          <label class="form-label">Select Board</label>
          
          <!-- 父级板块选择 -->
          <div class="board-select-group">
            <label class="sub-label">Parent Board</label>
            <el-select
              v-model="formData.parentBoardId"
              placeholder="Please select a parent board"
              size="large"
              style="width: 100%; margin-bottom: 15px;"
            >
              <el-option
                v-for="board in parentBoardOptions"
                :key="board.value"
                :label="board.label"
                :value="board.value"
              />
            </el-select>
          </div>
          
          <!-- 子级板块选择 -->
          <div class="board-select-group">
            <label class="sub-label">Sub Board</label>
            <el-select
              v-model="formData.boardId"
              placeholder="Please select a sub board"
              size="large"
              style="width: 100%"
              :disabled="!formData.parentBoardId"
            >
              <el-option
                v-for="board in currentChildBoards"
                :key="board.value"
                :label="board.label"
                :value="board.value"
              />
            </el-select>
          </div>
        </div>

        <!-- 文章到期时间 -->
        <div class="form-item">
          <div class="article-expire-time">
            <label class="sub-label">Article Expire Time</label>
            <el-date-picker
                v-model="formData.expireTime"
                type="datetime"
                placeholder="Select expire time (optional)"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                size="large"
                style="width: 100%;"
                :disabled-date="(time) => time.getTime() < Date.now() - 24 * 60 * 60 * 1000"
            />
          </div>
        </div>

        <!-- 发布为通知选项 -->
        <div class="form-item" v-if="currentUser.hasTopPostPermission">
          <div class="notice-option">
            <el-checkbox 
              v-model="formData.isNotice"
              size="large"
            >
              Publish as Notice
            </el-checkbox>
          </div>
          
          <!-- 通知到期时间选择器 -->
          <div class="notice-expire-time">
            <label class="sub-label">Notice Expire Time</label>
            <el-date-picker
              v-model="formData.topExpireTime"
              type="datetime"
              placeholder="Select expire time (optional)"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              size="large"
              :disabled="!formData.isNotice"
              style="width: 100%;"
              :disabled-date="(time) => time.getTime() < Date.now() - 24 * 60 * 60 * 1000"
            />
            <div class="expire-time-tip">
              Leave empty for permanent notice
            </div>
          </div>
        </div>

        <!-- 允许评论选项 -->
        <div class="form-item">
          <div class="comment-option">
            <el-checkbox 
              v-model="formData.allowComment"
              size="large"
            >
              Allow Comment
            </el-checkbox>
          </div>
        </div>

        <!-- 按钮 -->
        <div class="button-group">
          <el-button
            type="primary"
            size="large"
            @click="submitPost"
            class="submit-btn"
            :loading="submitLoading"
          >
            {{ isEditMode ? 'Update Post' : 'Publish Post' }}
          </el-button>
          <el-button
            size="large"
            @click="cancelPost"
            class="cancel-btn"
          >
            Cancel
          </el-button>
        </div>

        <!-- 发帖提示 -->
        <div class="post-tips">
          <div class="tips-title">Posting Guidelines</div>
          <ul class="tips-list">
            <li>Please follow community guidelines and speak civilly</li>
            <li>Content should be detailed and provide valuable information</li>
            <li>Choose appropriate board for better categorization</li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.edit-post-body {
  width: 1300px;

  .board-info {
    color: #9ba7b9;
    line-height: 35px;

    .icon-right {
      padding: 0px 5px;
    }
  }
  
  .edit-container {

    display: flex;
    gap: 20px;
    
    .left-panel {
      flex: 1;
      padding: 20px;
      background: #fff;

      .form-item {
        margin-bottom: 25px;
        
        .form-label {
          display: block;
          font-size: 16px;
          font-weight: 600;
          color: #333;
          margin-bottom: 8px;
        }
        
        .board-select-group {
          .sub-label {
            display: block;
            font-size: 14px;
            font-weight: 500;
            color: #606266;
            margin-bottom: 8px;
            display: block;
          }
          
          /* 通知选项样式 */
          .notice-option {
            display: flex;
            flex-direction: column;
            gap: 12px;
          }
        }
        
        .upload-container {
          display: flex;
          align-items: center;
          gap: 15px;
          margin-bottom: 15px;
          
          .upload-tip {
            font-size: 12px;
            color: #999;
          }
        }
        
        .image-preview {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
          
          .preview-item {
            position: relative;
            width: 120px;
            height: 120px;
            border-radius: 8px;
            overflow: hidden;
            border: 1px solid #ddd;
            
            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
            
            .preview-overlay {
              position: absolute;
              top: 0;
              left: 0;
              right: 0;
              bottom: 0;
              background: rgba(0, 0, 0, 0.5);
              display: flex;
              align-items: center;
              justify-content: center;
              opacity: 0;
              transition: opacity 0.3s;
            }
            
            &:hover .preview-overlay {
              opacity: 1;
            }
            
            &.deleted-preview {
              opacity: 0.5;
              filter: grayscale(100%);
              pointer-events: none;
            }
          }
        }
      }
    }
    
    .right-panel {
      width: 400px;
      flex-shrink: 0;
      background: #fff;
      padding: 20px;

      .form-item {
        margin-bottom: 5px;
        
        .form-label {
          display: block;
          font-size: 16px;
          font-weight: 600;
          color: #333;
          margin-bottom: 8px;
        }
      }
      
      .button-group {
        margin-bottom: 30px;
        
        .submit-btn,
        .cancel-btn {
          width: 100%;
          margin: 0;
        }
        
        .submit-btn {
          margin-bottom: 10px;
        }
      }
      
      .post-tips {
        background: #f8f9fa;
        padding: 15px;
        border-radius: 8px;
        border-left: 4px solid #409EFF;
        
        .tips-title {
          font-size: 14px;
          font-weight: 600;
          color: #333;
          margin-bottom: 10px;
        }
        
        .tips-list {
          margin: 0;
          padding-left: 20px;
          
          li {
            font-size: 12px;
            color: #666;
            line-height: 1.6;
            margin-bottom: 5px;
          }
        }
      }

      .notice-expire-time {
        .sub-label {
          display: block;
          font-size: 14px;
          font-weight: 500;
          color: #606266;
          margin-bottom: 8px;
        }
        
        .expire-time-tip {
          font-size: 12px;
          color: #999;
          margin-top: 5px;
        }
      }

      // 文章到期时间样式
      .article-expire-time {
        .sub-label {
          display: block;
          font-size: 14px;
          font-weight: 500;
          color: #606266;
          margin-bottom: 8px;
        }
        
        .expire-time-tip {
          font-size: 12px;
          color: #999;
          margin-top: 5px;
        }
      }
    }
  }
}

// Responsive design
@media (max-width: 1024px) {
  .edit-post-body {
    width: 100%;
    padding: 0 20px;
    
    .edit-container {
      flex-direction: column;
      
      .right-panel {
        width: 100%;
      }
    }
  }
}
</style>